package com.nowcoder.community.controller;

import ch.qos.logback.core.util.StringUtil;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.util.CommunityUtils;
import com.nowcoder.community.util.HostHolder;
import org.apache.catalina.Host;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("/discusspost")
public class DiscussPostController {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private HostHolder hostHolder;

    @RequestMapping(path = "/add",method = RequestMethod.POST)
    @ResponseBody
    public String addDiscussPost(String title, String content) {
        User user =hostHolder.getUser();
        if (user==null) {
            return CommunityUtils.getJsonString(403,"未登录，无法操作！");
        }
        if(StringUtil.isNullOrEmpty(title) || StringUtil.isNullOrEmpty(content)) {
            return CommunityUtils.getJsonString(404,"不能为空！");
        }
        DiscussPost post =new DiscussPost();
        post.setTitle(title);
        post.setContent(content);
        post.setCreateTime(new Date());
        post.setUserId(user.getId());
        int a =discussPostService.addDiscussPost(post);
        if (a==1) {
            return CommunityUtils.getJsonString(0,"帖子发布成功！");
        }
        return CommunityUtils.getJsonString(404,"帖子发布失败！");
    }

}
